'use strict';
const bcrypt = require('bcryptjs');

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    username: {
      type: DataTypes.STRING,
      unique: true,
      allowNull: true,
      comment: '用户名'
    },
    password: {
      type: DataTypes.STRING,
      allowNull: true,
      comment: '密码（加密后）'
    },
    openid: {
      type: DataTypes.STRING,
      unique: true,
      allowNull: true,
      comment: '小程序 openid'
    },
    nickname: {
      type: DataTypes.STRING,
      allowNull: true,
      comment: '昵称'
    },
    avatar: {
      type: DataTypes.STRING,
      allowNull: true,
      comment: '头像'
    },
    phone: {
      type: DataTypes.STRING,
      allowNull: true,
      comment: '手机号'
    },
    points: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      comment: '积分'
    },
    balance: {
      type: DataTypes.DECIMAL(10, 2),
      defaultValue: 0.00,
      comment: '余额'
    },
    is_vip: {
      type: DataTypes.BOOLEAN,
      defaultValue: false,
      comment: '是否是 VIP'
    },
    role: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: 'user',
      comment: '用户角色（admin/user）'
    }
  }, {
    tableName: 'users',
    // ✅ 启用模型级别钩子
    hooks: {
      beforeCreate: async (user) => {
        await hashPassword(user);
      },
      beforeUpdate: async (user) => {
        // 只有当密码发生变化时才加密
        if (user.changed('password')) {
          await hashPassword(user);
        }
      }
    }
  });

  /**
   * 私有封装：统一密码加密逻辑
   */
  async function hashPassword(user) {
    if (user.password) {
      const saltRounds = 10;
      user.password = await bcrypt.hash(user.password, saltRounds);
    }
  }

  return User;
};
